package com.running.base.run.mq;

import com.rabbitmq.client.Channel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Random;

@Component
public class RabbitMqReceiver {

    private static final Logger logger = LoggerFactory.getLogger(RabbitMqReceiver.class);

    public static final String QUEUE_NAME = "run-fudao-queue";

    @RabbitListener(queues = QUEUE_NAME)
    public void listenMessage(Message message, Channel channel) throws IOException, InterruptedException, IOException {
        // 消息投递序号，消息每次投递该值都会+1
        long deliveryTag = message.getMessageProperties().getDeliveryTag();
        try {
            //模拟bug
            logger.info("成功接受到消息:" + message);

            if (new Random().nextInt(10) % 2 == 0) {
                throw new Exception("random exception.");
            }

            // 签收消息
            /**
             * 参数1：消息投递序号
             * 参数2：是否一次可以签收多条消息
             */
            channel.basicAck(deliveryTag,true);
        }catch (Exception e){
            logger.info("消息消费失败！准备重新消费...");
            // 拒签消息
            /**
             * 参数1：消息投递序号
             * 参数2：是否一次可以拒签多条消息
             * 参数3：拒签后消息是否重回队列
             */
            channel.basicNack(deliveryTag,true,true);
        }
    }
}


